package com.wzx.ptplatform.service.impl;

import com.wzx.ptplatform.dao.WorkExperienceDao;
import com.wzx.ptplatform.domain.WorkExperience;
import com.wzx.ptplatform.service.WorkExperienceService;
import com.wzx.ptplatform.utils.PageUtils;
import com.wzx.ptplatform.utils.PtplatformException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.util.List;

/**
 * @author 紫煦桉
 */
@Service
public class WorkExperienceServiceImpl implements WorkExperienceService {

    @Resource
    private WorkExperienceDao workExperienceDao;

    @Override
    public Page<WorkExperience> findList(WorkExperience workExperience, Integer page, Integer limit) throws PtplatformException {
        Specification<WorkExperience> spec = (Specification<WorkExperience>) (root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            List<Expression<Boolean>> exList = predicate.getExpressions();//动态SQL表达式集合
            if (workExperience.getResume() != null) {
                exList.add(criteriaBuilder.equal(root.get("resume").get("id").as(Long.class), workExperience.getResume().getId()));
            }
            return predicate;
        };
        PageRequest pageRequest = PageUtils.initPageRequest();
        PageRequest pageable = PageUtils.setPageable(0, Math.toIntExact(workExperienceDao.findAll(spec, pageRequest).getTotalElements()));
        if (page != null && limit != null) {
            PageRequest parable = PageUtils.setPageable(page, limit);
            return workExperienceDao.findAll(spec, parable);
        }
        return workExperienceDao.findAll(spec, pageable);
    }

    @Override
    public WorkExperience findById(long id) throws PtplatformException {
        return workExperienceDao.findById(id).orElse(null);
    }

    @Override
    public boolean saveOrEdit(WorkExperience workExperience) throws PtplatformException {
        try {
            workExperienceDao.saveAndFlush(workExperience);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteById(long id) throws PtplatformException {
        try {
            workExperienceDao.deleteById(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
